package com.bootdo.rabbitMQ.topic;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.rabbitMQ.direct.DirectNews;
import com.bootdo.rabbitMQ.entity.MessageVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @Author wukq
 * @Date: 2021/4/10 16:28
 * @Description:
 */
@Component
@RabbitListener(queues = TopicConstant.TOPIC_LEFT_QUEUE)//监听队列
public class TopicLeftConsumer {


  @Autowired
  private CachingConnectionFactory connectionFactory;

  @RabbitHandler
  public void process(String s, Message message, Channel channel) throws Exception {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setConcurrentConsumers(2);
    factory.setMaxConcurrentConsumers(10);
    factory.setPrefetchCount(1);
    factory.setDefaultRequeueRejected(true);
    //手动确认
    factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
    byte[] body = message.getBody();
    String bodyString = new String(body);

    MessageVo messageVo = JSONObject.parseObject(bodyString, MessageVo.class);
    String msg = messageVo.getMsg();
    List<DirectNews> directNews = JSONObject.parseArray(msg, DirectNews.class);
    for (DirectNews news : directNews) {
      System.out.println("-----right 接受到的消息----" + news.toString());
    }
    try {
      channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);//消费消息确认

    } catch (IOException e) {
      e.printStackTrace();
      channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
    }
  }


}
